#include <stdio.h>
double legendre(int n, double x);
int main() 
{
    int n;
    double x;

    printf("请输入 n（非负整数）: ");
    scanf("%d", &n);

    printf("请输入 x 的值: ");
    scanf("%lf", &x);

    if (n < 0) {
        printf("错误：n 必须是非负整数。\n");
        return 1;
    }

    double result = legendre(n, x);
    printf("P_%d(%.2f) = %.6f\n", n, x, result);

    return 0;
}

double legendre(int n, double x) {
    if (n == 0)
        return 1.0;  // P0(x) = 1
    else if (n == 1)
        return x;    // P1(x) = x
    else
        return ((2 * n - 1) * x * legendre(n - 1, x) - (n - 1) * legendre(n - 2, x)) / n;
}